import store from '@/store'

export function actionToObject (json) {
  try {
    return JSON.parse(json)
  } catch (e) {
    console.log('err', e.message)
  }
  return []
}

/**
 * 控制按钮是否显示
 *
 * @author yubaoshan
 * @date 2020/06/27 02:34
 */
export function hasBtnPermission (permission) {
  const myBtns = store.getters.buttons
  const admintype = store.getters.admintype
  // eslint-disable-next-line eqeqeq
  if (admintype == '1') {
     return true
  }
  return myBtns.indexOf(permission) > -1
}


/**
 * 按钮权限校验
 * @param {Array} value 校验值
 * @returns {Boolean}
 */
export function hasPermi(value) {
  if (value && value instanceof Array && value.length > 0) {
    console.log('getters', store.getters)

    // 每个项目的接口返回数据以及数据处理都不太一样，所以要根据接口的数据进行微调
    // 一开始报错是因为permissions不在getters中，而是在getters.userInfo中
    // const permissions = store.getters && store.getters.permissions

    let permissions = store.getters?.userInfo?.permissions
    permissions = permissions || []
    const permissionDatas = value
    const all_permission = "*:*:*";

    const hasPermission = permissions.some(item => {
      return all_permission == item || permissionDatas.includes(item)
    })

    if (!hasPermission) {
      return false
    }
    return true
  } else {
    console.error(`未传数据或数据类型错误或数组长度为0`)
    return false
  }
}


/**
 * 单账户多角色时，使用该方法可过滤角色不存在的菜单
 *
 * @param roles
 * @param route
 * @returns {*}
 */
// eslint-disable-next-line
export function hasRole(roleId) {
	console.log("roleId-------",roleId);
	
  let getters = store.getters
  let roles1 = store.getters.roles[0]
  let roleIds = getters.userInfo.roleIds
  // console.log('roleIds-------', roleIds)
  if (roleIds.indexOf(roleId) === -1) {
    return false
  } else {
    return true
  }
}



// 角色权限校验(拥有其中一个角色就返回true)
export function hasRoleNoAdmin(value) {
	if (value && value instanceof Array && value.length > 0) {
		const rolesList = value

		let roles = store.getters?.userInfo?.roles
		let roleCodes = roles.map(item => item.code)

		const hasRole = roleCodes.some(code => {
      return rolesList.includes(code)
    })
    return hasRole
	}else {
    console.error(`need roles! Like checkRole="['admin','editor']"`)
    return false
  }
}


//判断是否没有所传过来的角色，如果传多个，必须同时没有才返回true
export function hasRoleNo(value) {
  if (value && value instanceof Array && value.length > 0) {
		const rolesList = value

		let roles = store.getters?.userInfo?.roles
		let roleCodes = roles.map(item => item.code)

		const hasRole = roleCodes.every(code => {
      return rolesList.indexOf(code) === -1
    })
    return hasRole
	}else {
    console.error(`need roles! Like checkRole="['admin','editor']"`)
    return false
  }
}
